package com.lieve.tx.proxy;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author sunyoboy
 * 2020/9/20
 */
public class CglibProxyTest {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(CglibProxyService.class);
        enhancer.setCallback(new CglibProxyInterceptor());
        CglibProxyService proxy = (CglibProxyService)enhancer.create();
        System.out.println(CglibProxyService.class);
        System.out.println(proxy.getClass());
        proxy.sayHello();
    }

    static class CglibProxyService {
        public CglibProxyService() {
        }

        void sayHello() {
            System.out.println("Hello !");
        }
    }

    static class CglibProxyInterceptor implements MethodInterceptor {
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("before");
            Object obj = methodProxy.invokeSuper(o, objects);
            System.out.println("after");
            return obj;
        }
    }
}
